package fd.sudoku.data;

import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import fd.sudoku.utility.SudokuCheck;

public class SudokuMap {

	private HashMap<Integer, SudokuNumber> theSudokuMap = new HashMap<Integer, SudokuNumber>();
	
	public HashMap<Integer, SudokuNumber> getTheSudokuMap() {
		return theSudokuMap;
	}

	public void setTheSudokuMap(HashMap<Integer, SudokuNumber> theSudokuMap) {
		this.theSudokuMap = theSudokuMap;
	}

	public SudokuMap(List<String> numbers)
	{
		int total = numbers.size();
		int lineSize = (int) Math.sqrt(total);
		int count = 0;
		for(String numberString : numbers)
		{
			int row = count%lineSize;
			int line = count/lineSize + 1;
			int value = -1;
			
			if(numberString != null && numberString.trim().length()>0)
			{
				value = Integer.parseInt(numberString);
			}
			SudokuNumber sudokuNumber = new SudokuNumber(line,row + 1, value);
			theSudokuMap.put(10*line + row + 1, sudokuNumber);
			count++;
		}
	}
	
	public SudokuMap() {
		// TODO Auto-generated constructor stub
	}
	
	public void set(int line, int row, SudokuNumber sudokuNumber)
	{
		theSudokuMap.put(line*10+row, sudokuNumber);
	}

	public SudokuNumber get(int line, int row)
	{
		return theSudokuMap.get(line*10+row);
	}
	
	@Override
	public String toString()
	{
		String output = " --- --- --- --- --- --- --- --- ---\r\n";
		for(int i = 1 ; i <= SudokuCheck.LINESIZE ; i++)
		{
			output += "| ";
			for(int j = 1 ; j <= SudokuCheck.ROWSIZE ; j++)
			{
				SudokuNumber sudokuNumber = theSudokuMap.get(i*10+j);
				if(sudokuNumber != null && sudokuNumber.getValue() > 0)
				{
					output += String.valueOf(sudokuNumber.getValue());
				}
				else if(sudokuNumber == null)
				{
					System.err.println(String.valueOf(i*10+j) + " has no value!");
				}
				else
				{
					output += " ";
				}
				output += " | ";
			}
			output += "\r\n";
			output += " --- --- --- --- --- --- --- --- ---\r\n";
		}
		return output;
	}
	
	@Override
	public SudokuMap clone()
	{
		SudokuMap maps = new SudokuMap();
		HashMap<Integer, SudokuNumber> theMap = new HashMap<Integer, SudokuNumber>();
		Set<Entry<Integer, SudokuNumber>> set = theSudokuMap.entrySet();
		for(Entry<Integer, SudokuNumber> entry : set)
		{
			theMap.put(entry.getKey(), entry.getValue());
		}
		maps.setTheSudokuMap(theMap);
		return maps;
		
	}

	public void set(int line, int row, int value) 
	{
		SudokuNumber sudokuNumber = new SudokuNumber(line,row,value);
		set(line,row,sudokuNumber);
	}
}
